package com.antexpress.controller;

import com.antexpress.bean.FormatValidate;
import com.antexpress.bean.VerifyCode;
import com.antexpress.common.Const;
import com.antexpress.common.Response;
import com.antexpress.pojo.Employee;
import com.antexpress.service.EmployeeService;
import com.antexpress.util.GraphicUtil;
import com.antexpress.util.MD5Util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Andy
 */
@Controller
@RequestMapping(value="/emp/")
public class EmployeeController {
    @Autowired
    private EmployeeService empService;
    
    @RequestMapping(value="update_password.do", method=RequestMethod.POST)
    @ResponseBody
    public Response updatePassword(String oldPassword, String newPassword, HttpSession session) {
        Response resp = null;
        Employee e = (Employee)session.getAttribute(Const.CURRENT_USER);
        Employee employee = (Employee) e.clone();
        if(employee!=null) {
            if(employee.getPassword().equals(MD5Util.MD5EncodeUtf8(oldPassword))){
                if(newPassword.length()>=6&&newPassword.length()<=12){
                    employee.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
                    resp = empService.updateProfile(employee);
                    if(resp.isSuccess())
                        session.setAttribute(Const.CURRENT_USER, employee);
                }else {
                    resp = Response.createByErrorMessage("New password is too short or too long!");
                }
            }else {
                resp = Response.createByErrorMessage("Your current password is wrong!");
            }
        }else {
            resp = Response.createByErrorMessage("Not login!");
        }
        return resp;
    }
    
    /*修改个人基本信息*/
    @RequestMapping(value="update_profile.do",method = RequestMethod.POST)
    @ResponseBody
    public Response updateProfile(String name, String gender, String mobile, String email, Date birth, HttpSession session) {
        Response resp = null;
        Employee e = (Employee)session.getAttribute(Const.CURRENT_USER);
        Employee employee = (Employee) e.clone();
        if(employee!=null) {
            if(FormatValidate.isNameTooShort(name))
                resp = Response.createByErrorMessage("Name is too short!");
            else if(FormatValidate.isNameTooLong(name))
                resp = Response.createByErrorMessage("Name is too long(No more than 50 letters)!");
            else if(!FormatValidate.isGender(gender))
                resp = Response.createByErrorMessage("Gender is not conformed to the regulations!");
            else if(!mobile.equals("")&&!FormatValidate.isPhoneLegal(mobile))
                resp = Response.createByErrorMessage("Mobile is not conformed to the regulations!");
            else if(!email.equals("")&&!FormatValidate.checkEmail(email))
                resp = Response.createByErrorMessage("Emial is not conformed to the regulations!");
            else if(!FormatValidate.isBirthAllowed(birth))
                resp = Response.createByErrorMessage("Age must be more than 18 years old!");
            else{
                employee.setName(name);
                employee.setGender(gender);
                employee.setMobile(mobile);
                boolean isEmailExisted = false;
                if(!email.equals(employee.getEmail())){
                    if(email!=null&&!email.equals(""))
                        isEmailExisted = empService.isEmailExisted(email);
                    else
                        employee.setEmail(null);
                }
                employee.setBirth(birth);
                if(isEmailExisted)
                    resp = Response.createByErrorMessage("Sorry, the email has been used!");
                else{
                    employee.setEmail(email);
                    resp = empService.updateProfile(employee);
                }
                if(resp.isSuccess()){
                    session.setAttribute(Const.CURRENT_USER, employee);
                }
            }
        }else {
            resp = Response.createByErrorMessage("Not login!");
        }
        return resp;
    }
    
    /*获取登录验证码*/
    @RequestMapping(value="login_verifycode.do",method=RequestMethod.GET)
    public void getLoginVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();  
        final int width = 120; // 图片宽度  
        final int height = 35; // 图片高度  
        final String imgType = "jpeg"; 
        
        VerifyCode verifyCode = GraphicUtil.create(width, height, imgType);  
        session.setAttribute(Const.LOGIN_VERIFY_CODE, verifyCode.getCode());
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        ImageIO.write(verifyCode.getImage(), imgType, out);
        byte[] imgByte = out.toByteArray();
        OutputStream stream = response.getOutputStream();
        stream.write(imgByte);  
        stream.flush();  
        stream.close();  
    }
    
    /*员工登录接口*/
    @RequestMapping(value="login.do", method=RequestMethod.POST)
    @ResponseBody
    public Response login(String username, String password, String verifycode, boolean remember, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Response resp = null;
        String codeInSession = (String) session.getAttribute(Const.LOGIN_VERIFY_CODE);
        if(codeInSession != null && codeInSession.equalsIgnoreCase(verifycode)) {
            resp = empService.login(username, password);
            if(resp.isSuccess()) {
                Employee emp = (Employee) resp.getData();
                if(remember==true){
                    session.setMaxInactiveInterval(60*60*24*7);
                    Cookie c=new Cookie("JSESSIONID", session.getId());
                    c.setPath(request.getContextPath());
                    c.setMaxAge(60*60*24*7);
                    response.addCookie(c);
                }
                session.setAttribute(Const.CURRENT_USER, emp);
                resp = Response.createBySuccessMessage("Login succeed!");
            }
        }else {
            resp = Response.createByErrorMessage("Incorrect verify code!");
        }
        return resp;
    }
    
    /*退出登录*/
    @RequestMapping(value="logout.do", method=RequestMethod.POST)
    @ResponseBody
    public Response logout(HttpSession session) {
        Response resp = null;
        if(session.getAttribute(Const.CURRENT_USER)==null){
            resp = Response.createByErrorMessage("Not login!");
        }else {
            session.removeAttribute(Const.CURRENT_USER);
            resp = Response.createBySuccess("Logout succeed!");
        }
        return resp;
    }
}
